package com.ywqf_api.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.ywqf_api.common.enums.FilePaths;

/**
 * 上传文件工具类
 * @author ran
 *
 */
@Component
public class UploadUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(UploadUtil.class);
	
    private static String docBase;
    
    private static String virtualPath;
    
    private static final String SEPARATOR = File.separator;
    
    private static final String PATTERN = "yyyyMMddHHmmssSSS";
    
    /**
     * 生成文件的访问相对路径
     * @return
     */
    private static String getAccessPath(FilePaths filePath,String fileName){
    	return virtualPath + SEPARATOR + filePath.getPath() + SEPARATOR + fileName;
    }
    
    /**
     * 生成文件在服务器上的绝对路径
     * @param filePath
     * @param fileName
     * @return
     */
    private static String getAbsolutePath(FilePaths filePath,String fileName){
    	return docBase + SEPARATOR + filePath.getPath() + SEPARATOR + fileName;
    }
    
    /**
     * 保存文件并返回文件的访问路径
     * @param multipartFile
     * @param filePath
     * @return 返回null 则文件保存失败
     */
    public static String saveFile(MultipartFile multipartFile,FilePaths filePath){
    	String fileName = multipartFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(fileName);
        fileName = randomFileName() + "." + "png";
        try {
			multipartFile.transferTo(new File(getAbsolutePath(filePath, fileName)));
		} catch (IllegalStateException | IOException e) {
			logger.error("保存上传的文件失败",e);
			return null;
		}
    	return getAccessPath(filePath, fileName);
    }
    
    /**
     * 生成随机文件名 yyyyMMddHHmmssSSS+5位随机数
     * @return
     */
    private static String randomFileName(){
    	String time = new SimpleDateFormat(PATTERN).format(new Date());
    	int rannum = (int) (new Random().nextDouble() * (99999 - 10000 + 1)) + 10000;
    	return rannum + time;
    }
    
    public static void setDocBaseAndVirtualPath(String docBase, String virtualPath){
    	UploadUtil.docBase = docBase;
    	UploadUtil.virtualPath = virtualPath;
    }
}
